import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { ref, computed } from 'vue'
import dayjs from 'dayjs'
console.log(dayjs.unix(100).format('mm分ss秒'))

export function useObserver (apiFn) {
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    // target 是观察的目标dom容器，必须是dom容器，而且是vue3.0方式绑定的dom对象
    target,
    // isIntersecting 是否进入可视区域，true是进入 false是移出
    // observerElement 被观察的dom
    ([{ isIntersecting }], observerElement) => {
      // 在此处可根据isIntersecting来判断，然后做业务
      console.log(isIntersecting)
      if (isIntersecting) {
        stop()
        apiFn()
      }
    }
  )

  return target
}

export function useCountDown (startCount) {
  const countTime = ref(0)

  const { pause, resume } = useIntervalFn(() => {
    if (countTime.value <= 0) {
      pause()
      return
    }
    countTime.value--
  }, 1000)
  const countTimeText = computed(() => {
    return dayjs.unix(countTime.value).format('mm分ss秒')
  })

  const start = (newStartCount) => {
    countTime.value = newStartCount || startCount
    resume()
  }
  return {
    countTime,
    countTimeText,
    start,
    pause,
    resume
  }
}
